﻿//==============================================================================
// File: MenuItemBasedContextMenuItemFactory.cs
// Created: 2010-04-30
// Author: Piotr Włodek
//==============================================================================
// This file is a part of MAMMOTH project.
// Copyright (C) 2010 AGH University of Science and Technology, Krakow.
// https://caribou.iisg.agh.edu.pl/trac/mammoth
//
// Mammoth is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// Mammoth is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with Mammoth. If not, see http://www.gnu.org/licenses/.
//==============================================================================

using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WpfRcp.Core.Services.Commands
{
    public class MenuItemBasedContextMenuItemFactory : IContextMenuItemFactory
    {
        public ItemsControl GetVisualItem(IMenuItem item, IMenuItemGroup menuItemGroup, ICommandDescriptor commandDescriptor)
        {
            var menuItem = new MenuItem { Header = item.Text };

            if (commandDescriptor != null)
            {
                menuItem.Command = commandDescriptor.Command;
                menuItem.InputGestureText = string.Empty;

                if (commandDescriptor.KeyGestures.Count > 0)
                {
                    var gesture = new KeyGesture(commandDescriptor.KeyGestures[0].Key, commandDescriptor.KeyGestures[0].ModifierKey);
                    Application.Current.MainWindow.InputBindings.Add(new InputBinding(menuItem.Command, gesture));
                    menuItem.InputGestureText = gesture.GetDisplayStringForCulture(Thread.CurrentThread.CurrentCulture);
                }
            }
            else
            {
                menuItem.IsEnabled = false;
            }

            return menuItem;
        }
    }
}